package com.Web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.StringUtil;

import com.entity.Employee;
import com.service.LoginService;

public class login extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String method = request.getParameter("m");
		if (StringUtil.isEmpty(method)) {
			request.getRequestDispatcher("/WEB-INF/views/index.jsp").forward(
					request, response);
		} else if ("login".equals(method)) {
			if ("POST".equals(request.getMethod())) {
				login(request, response);
			} else {
				response.sendError(405);
			}
		}

	}

	private void login(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		String username = request.getParameter("username");
		String password = request.getParameter("password");

		LoginService service = new LoginService();
		Employee em = service.login(username, password);
		if (em == null) {
			response.sendRedirect("index.jsp?state=10001");
		} else {
			HttpSession session = request.getSession();

			session.setAttribute("em", em);

			response.sendRedirect("mainServlet.jspx");
		}

	}
}
